
const fs = require('fs');
const path = require('path');
const db = require('../config/db');
const moment = require('moment');

// 工具函数：格式化日期时间
const formatDateTime = (date) => {
  return moment(date).format('YYYY-MM-DD HH:mm:ss');
};

// 获取所有商品分类（扁平结构）
exports.getAllCategories = async (req, res) => {
  try {
    console.log(`[${formatDateTime(new Date())}] [INFO] 获取所有商品分类请求`);
    const [categories] = await db.query('SELECT category_id, name, icon_url FROM categories');
    res.json({ categories: categories });
  } catch (err) {
    console.error(`[${formatDateTime(new Date())}] [ERROR] 获取分类失败: ${err.message}`);
    res.status(500).json({ message: '获取分类失败', error: err.message });
  }
};

// 获取用户发布商品的分类（需认证）
exports.getUserCategories = async (req, res) => {
  try {
    console.log(`[${formatDateTime(new Date())}] [INFO] 获取用户发布商品分类请求: 用户ID=${req.user.user_id}`);
    const userId = req.user.user_id;
    // 查询用户发布过商品的所有分类
    const [userCategories] = await db.query(
      'SELECT DISTINCT c.category_id, c.name, c.icon_url FROM categories c JOIN products p ON c.category_id = p.category_id WHERE p.seller_id = ?',
      [userId]
    );
    res.json({ categories: userCategories });
  } catch (err) {
    console.error(`[${formatDateTime(new Date())}] [ERROR] 获取用户分类失败: ${err.message}`);
    res.status(500).json({ message: '获取用户分类失败', error: err.message });
  }
};

// 获取用户发布的商品（需认证，支持分页）
exports.getMyProducts = async (req, res) => {
  try {
    const { page = 1, pageSize = 10 } = req.query;
    const currentPage = parseInt(page, 10);
    const itemsPerPage = parseInt(pageSize, 10);
    const offset = (currentPage - 1) * itemsPerPage;
    
    console.log(`[${formatDateTime(new Date())}] [INFO] 获取用户发布商品请求: 用户ID=${req.user.user_id}, 页码=${currentPage}, 每页数量=${itemsPerPage}`);
    const userId = req.user.user_id;
    
    // 查询商品数据
    const [rows] = await db.query(
      `SELECT p.*, (SELECT image_url FROM product_images WHERE product_id = p.product_id AND sort_order = 0 LIMIT 1) AS image_url FROM products p
       WHERE p.seller_id = ?
       GROUP BY p.product_id
       ORDER BY p.created_at DESC
       LIMIT ? OFFSET ?`,
      [userId, itemsPerPage, offset]
    );
    
    // 查询总数量
    const [countResult] = await db.query(
      `SELECT COUNT(DISTINCT p.product_id) as total FROM products p
       WHERE p.seller_id = ?`,
      [userId]
    );
    
    const totalItems = countResult[0].total;
    const totalPages = Math.ceil(totalItems / itemsPerPage);
    
    res.json({
      products: rows,
      pagination: {
        currentPage,
        pageSize: itemsPerPage,
        totalItems,
        totalPages
      }
    });
  } catch (err) {
    console.error(`[${formatDateTime(new Date())}] [ERROR] 获取商品失败: ${err.message}`);
    res.status(500).json({ message: '获取商品失败', error: err.message });
  }
};

// 发布商品
exports.createProduct = async (req, res) => {
  try {
    console.log(`[${formatDateTime(new Date())}] [INFO] 发布商品请求: ${JSON.stringify(req.body)}`);
    const userId = req.user.user_id;
    const { title, description, price, original_price, category_id } = req.body;
    
    if (!title || !description || !price || !category_id) {
      return res.status(400).json({ message: '信息不完整' });
    }
    // 插入商品基本信息（不含图片），设置默认状态为0（审核中）
    const [productResult] = await db.query(
      'INSERT INTO products (seller_id, title, description, price, original_price, category_id, status, created_at) VALUES (?, ?, ?, ?, ?, ?, 0, NOW())',
      [userId, title, description, price, original_price || null, category_id]
    );
    
    // 处理多张图片
    console.log(`[${formatDateTime(new Date())}] [INFO] [文件上传] 接收到 ${req.files ? req.files.length : 0} 张图片`);
    if (req.files && req.files.length > 0) {
      const imageUrls = [];
      for (let i = 0; i < req.files.length; i++) {
        const file = req.files[i];
        const image_url = '/uploads/products/' + file.filename;
        imageUrls.push([productResult.insertId, image_url, i]);
        console.log(`[${formatDateTime(new Date())}] [INFO] 图片上传成功: ${image_url}`);
      }
      
      // 批量插入图片
      await db.query(
        'INSERT INTO product_images (product_id, image_url, sort_order) VALUES ?',
        [imageUrls]
      );
      console.log(`[${formatDateTime(new Date())}] [INFO] 商品图片关联成功: product_id=${productResult.insertId}, 图片数量=${req.files.length}`);
    }
    
    res.json({ message: '发布成功' });
  } catch (err) {
    console.error(`[${formatDateTime(new Date())}] [ERROR] 发布失败: ${err.message}`);
    res.status(500).json({ message: '发布失败', error: err.message });
  }
};

// 按条件筛选商品（如分类、关键字、价格区间等，支持分页）
exports.filterProducts = async (req, res) => {
  try {
    const { keyword, min_price, max_price, condition, price_order, categoryId, page = 1, pageSize = 10 } = req.query;
    const currentPage = parseInt(page, 10);
    const itemsPerPage = parseInt(pageSize, 10);
    const offset = (currentPage - 1) * itemsPerPage;
    
    console.log(`[${formatDateTime(new Date())}] [INFO] 商品筛选请求: ${JSON.stringify(req.query)}`);
    const params = [];
    const countParams = [];
    
    // 构建商品数据SQL查询
    let sql = 'SELECT p.product_id, p.seller_id, p.category_id, p.title, p.description, CAST(p.price AS DECIMAL(10,2)) AS price, CAST(p.original_price AS DECIMAL(10,2)) AS original_price, p.status, p.view_count, p.created_at, p.updated_at, (SELECT image_url FROM product_images WHERE product_id = p.product_id AND sort_order = 0 LIMIT 1) AS image_url FROM products p WHERE 1=1';
    
    // 构建总数量SQL查询
    let countSql = 'SELECT COUNT(DISTINCT p.product_id) as total FROM products p WHERE 1=1';
    
    // 如果用户已登录，添加用户ID筛选条件
    if (req.user) {
      sql += ' AND p.seller_id = ?';
      countSql += ' AND p.seller_id = ?';
      params.push(req.user.user_id);
      countParams.push(req.user.user_id);
      console.log(`[${formatDateTime(new Date())}] [DEBUG] [商品筛选] 添加用户ID筛选条件: ${req.user.user_id}`);
    }
    
    if (keyword) {
      sql += ' AND (p.title LIKE ? OR p.description LIKE ?)';
      countSql += ' AND (p.title LIKE ? OR p.description LIKE ?)';
      params.push(`%${keyword}%`, `%${keyword}%`);
      countParams.push(`%${keyword}%`, `%${keyword}%`);
    }
    
    // 添加分类筛选条件
    if (categoryId) {
      sql += ' AND p.category_id = ?';
      countSql += ' AND p.category_id = ?';
      params.push(categoryId);
      countParams.push(categoryId);
    }
    
    // 商品状态筛选: 0-审核中, 1-在售, 2-已售, 3-下架
    if (condition !== undefined && condition !== '') {
      const status = parseInt(condition, 10);
      if (!isNaN(status) && status >= 0 && status <= 3) {
        sql += ' AND p.status = ?';
        countSql += ' AND p.status = ?';
        params.push(status);
        countParams.push(status);
      }
    }
    
    if (min_price) {
      sql += ' AND p.price >= ?';
      countSql += ' AND p.price >= ?';
      params.push(Number(min_price));
      countParams.push(Number(min_price));
    }
    
    if (max_price) {
      sql += ' AND p.price <= ?';
      countSql += ' AND p.price <= ?';
      params.push(Number(max_price));
      countParams.push(Number(max_price));
    }
    
    sql += ' GROUP BY p.product_id';
    
    if (price_order === 'asc') {
      sql += ' ORDER BY p.price ASC';
    } else if (price_order === 'desc') {
      sql += ' ORDER BY p.price DESC';
    } else {
      sql += ' ORDER BY p.created_at DESC';
    }
    
    // 添加分页参数
    sql += ' LIMIT ? OFFSET ?';
    params.push(itemsPerPage, offset);
    
    // 执行查询
    const [rows] = await db.query(sql, params);
    const [countResult] = await db.query(countSql, countParams);
    
    const totalItems = countResult[0].total;
    const totalPages = Math.ceil(totalItems / itemsPerPage);
    
    console.log(`[${formatDateTime(new Date())}] [INFO] 商品筛选结果: 数量=${rows.length}, 总数量=${totalItems}, 总页数=${totalPages}`);
    res.json({
      products: rows,
      pagination: {
        currentPage,
        pageSize: itemsPerPage,
        totalItems,
        totalPages
      }
    });
  } catch (err) {
    console.error(`[${formatDateTime(new Date())}] [ERROR] 筛选失败: ${err.message}`);
    res.status(500).json({ message: '筛选失败', error: err.message });
  }
};

/**
 * 删除商品（需认证）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.deleteProduct = async (req, res) => {
  try {
    const { id } = req.params;
    console.log(`[${formatDateTime(new Date())}] [DEBUG] 接收到的商品删除ID: ${id}`);
    const userId = req.user.user_id;

    // 验证商品所有权
    const [product] = await db.execute('SELECT * FROM products WHERE product_id = ? AND seller_id = ?', [id, userId]);
    if (product.length === 0) {
      return res.status(404).json({ success: false, error: '商品不存在或无权删除' });
    }

    // 获取商品图片信息
    const [images] = await db.execute('SELECT image_url FROM product_images WHERE product_id = ?', [id]);
    console.log(`[${formatDateTime(new Date())}] [DEBUG] 商品ID=${id}的图片查询结果: ${JSON.stringify(images)}`);
    if (images.length === 0) {
      console.log(`[${formatDateTime(new Date())}] [WARN] 未查询到商品ID=${id}的图片记录`);
    }

    // 执行删除
    await db.execute('DELETE FROM products WHERE product_id = ?', [id]);
    await db.execute('DELETE FROM product_images WHERE product_id = ?', [id]);

    // 删除服务器上的图片文件
    const uploadDir = path.join(__dirname, '../../uploads/products');
    console.log(`[${formatDateTime(new Date())}] [DEBUG] 图片上传目录: ${uploadDir}`);
    for (const image of images) {
      const imagePath = path.join(uploadDir, path.basename(image.image_url));
      console.log(`[${formatDateTime(new Date())}] [DEBUG] 尝试删除图片: ${imagePath}`);
      if (fs.existsSync(imagePath)) {
        fs.unlinkSync(imagePath);
        console.log(`[${formatDateTime(new Date())}] [INFO] [删除商品图片] 图片路径: ${imagePath}`);
      } else {
        console.log(`[${formatDateTime(new Date())}] [WARN] [删除商品图片] 图片不存在: ${imagePath}`);
      }
    }

    // 记录删除日志
    console.log(`[${formatDateTime(new Date())}] [INFO] [用户删除商品] 商品ID: ${id}, 操作人: ${userId}`);

    res.json({ success: true, message: '商品已成功删除' });
  } catch (error) {
    console.error(`[${formatDateTime(new Date())}] [ERROR] [用户删除商品失败] ${error.message}`);
    res.status(500).json({ success: false, error: '删除商品失败' });
  }
};

// 更新商品
/**
 * 更新商品信息（需认证）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.updateProduct = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.user_id;
    console.log(`[${formatDateTime(new Date())}] [INFO] 更新商品请求: 商品ID=${id}, 用户ID=${userId}`);
    console.log(`[${formatDateTime(new Date())}] [DEBUG] 请求参数: ${JSON.stringify(req.body)}`);

    // 1. 验证商品所有权
    const [product] = await db.execute('SELECT * FROM products WHERE product_id = ? AND seller_id = ?', [id, userId]);
    if (product.length === 0) {
      return res.status(404).json({ success: false, error: '商品不存在或无权更新' });
    }

    // 2. 更新商品基本信息
    const { title, description, price, original_price, category_id } = req.body;
    const updateData = [];
    let sql = 'UPDATE products SET ';

    if (title) { sql += 'title = ?, '; updateData.push(title); }
    if (description) { sql += 'description = ?, '; updateData.push(description); }
    if (price) { sql += 'price = ?, '; updateData.push(price); }
    if (original_price !== undefined) { sql += 'original_price = ?, '; updateData.push(original_price || null); }
    if (category_id) { sql += 'category_id = ?, '; updateData.push(category_id); }

    // 移除最后一个逗号和空格
    if (updateData.length > 0) {
      sql = sql.slice(0, -2);
    } else {
      // 如果没有基本信息更新，仍然需要设置更新时间
      sql += 'updated_at = NOW()';
    }

    sql += ', updated_at = NOW() WHERE product_id = ?';
    updateData.push(id);

    // 执行更新
    await db.execute(sql, updateData);
    console.log(`[${formatDateTime(new Date())}] [INFO] 商品基本信息更新成功: 商品ID=${id}`);

    // 3. 处理图片上传和删除
    // 3.1 处理被删除的图片
    const deletedImages = req.body.deleted_images ? JSON.parse(req.body.deleted_images) : [];
    console.log(`[${formatDateTime(new Date())}] [INFO] [文件上传] 接收到 ${deletedImages.length} 张待删除图片`);

    if (deletedImages.length > 0) {
      const uploadDir = path.join(__dirname, '../../uploads/products');

      // 删除指定的图片文件和数据库记录
      for (const imageUrl of deletedImages) {
        const imagePath = path.join(uploadDir, path.basename(imageUrl));
        if (fs.existsSync(imagePath)) {
          fs.unlinkSync(imagePath);
          console.log(`[${formatDateTime(new Date())}] [INFO] [删除指定图片] 图片路径: ${imagePath}`);
        }

        // 从数据库删除图片记录
        await db.execute('DELETE FROM product_images WHERE product_id = ? AND image_url = ?', [id, imageUrl]);
        console.log(`[${formatDateTime(new Date())}] [INFO] [删除指定图片记录] 商品ID=${id}, 图片URL=${imageUrl}`);
      }
    }

    // 3.2 处理新上传的图片
    // 如果没有新图片且没有删除任何图片，不需要处理
    if (req.body.no_new_images && deletedImages.length === 0) {
      console.log(`[${formatDateTime(new Date())}] [INFO] 没有新图片且没有删除任何图片，保留原图片`);
    } else if (req.files && req.files.length > 0) {
      // 处理多张新图片
      const imageUrls = [];
      for (let i = 0; i < req.files.length; i++) {
        const file = req.files[i];
        const image_url = '/uploads/products/' + file.filename;
        imageUrls.push([id, image_url, i + (deletedImages.length > 0 ? 0 : await getMaxSortOrder(id))]);
        console.log(`[${formatDateTime(new Date())}] [INFO] 新图片上传成功: ${image_url}`);
      }

      // 批量插入图片
      await db.query(
        'INSERT INTO product_images (product_id, image_url, sort_order) VALUES ?',
        [imageUrls]
      );
      console.log(`[${formatDateTime(new Date())}] [INFO] 商品新图片添加成功: 商品ID=${id}, 图片数量=${req.files.length}`);
    } else if (deletedImages.length > 0) {
      // 只有删除操作，没有新图片上传
      console.log(`[${formatDateTime(new Date())}] [INFO] 只有删除操作，没有新图片上传`);
    }

    // 辅助函数：获取最大排序序号
    async function getMaxSortOrder(productId) {
      const [result] = await db.execute('SELECT MAX(sort_order) as max_order FROM product_images WHERE product_id = ?', [productId]);
      return result[0].max_order !== null ? result[0].max_order + 1 : 0;
    }

    res.json({ success: true, message: '商品更新成功' });
  } catch (error) {
    console.error(`[${formatDateTime(new Date())}] [ERROR] [更新商品失败] ${error.message}`);
    res.status(500).json({ success: false, error: '更新商品失败' });
  }
};

// 获取商品详情
/**
 * 获取商品详情
 * @param {Object} req - 请求对象，包含商品ID参数
 * @param {Object} res - 响应对象
 * @returns {Promise<void>} - 返回商品详情数据
 */
exports.getProductDetail = async (req, res) => {
  try {
    const { id } = req.params;
    console.log(`[${formatDateTime(new Date())}] [INFO] 获取商品详情请求: 商品ID=${id}`);

    // 查询商品基本信息
    const [product] = await db.query(
      `SELECT p.*, u.username as seller_name, u.avatar_url as seller_avatar
       FROM products p
       LEFT JOIN users u ON p.seller_id = u.user_id
       WHERE p.product_id = ?`,
      [id]
    );

    if (product.length === 0) {
      return res.status(404).json({ message: '商品不存在' });
    }

    // 查询商品图片
    const [images] = await db.query(
      'SELECT image_url FROM product_images WHERE product_id = ? ORDER BY sort_order ASC',
      [id]
    );

    // 查询商品分类
    const [category] = await db.query(
      'SELECT name FROM categories WHERE category_id = ?',
      [product[0].category_id]
    );

    // 更新商品浏览量
    await db.query(
      'UPDATE products SET view_count = view_count + 1 WHERE product_id = ?',
      [id]
    );

    // 组装返回数据
    const productDetail = {
      ...product[0],
      category_name: category.length > 0 ? category[0].name : '',
      images: images.map(img => img.image_url)
    };

    console.log(`[${formatDateTime(new Date())}] [DEBUG] 返回商品详情数据: ${JSON.stringify(productDetail)}`);
    res.json({ product: productDetail });
  } catch (err) {
    console.error(`[${formatDateTime(new Date())}] [ERROR] 获取商品详情失败: ${err.message}`);
    res.status(500).json({ message: '获取商品详情失败', error: err.message });
  }
};

// 更新商品状态（需认证）
/**
 * 更新商品状态
 * @param {Object} req - 请求对象，包含商品ID参数和状态
 * @param {Object} res - 响应对象
 * @returns {Promise<void>} - 返回操作结果
 */
exports.updateProductStatus = async (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;
    const userId = req.user.user_id;
    console.log(`[${formatDateTime(new Date())}] [INFO] 更新商品状态请求: 商品ID=${id}, 状态=${status}, 用户ID=${userId}`);

    // 验证商品所有权
    const [product] = await db.execute('SELECT * FROM products WHERE product_id = ? AND seller_id = ?', [id, userId]);
    if (product.length === 0) {
      return res.status(404).json({ success: false, error: '商品不存在或无权操作' });
    }

    // 验证状态参数
    if (status === undefined || !Number.isInteger(status) || status < 0 || status > 3) {
      return res.status(400).json({ success: false, error: '无效的状态参数' });
    }

    // 执行更新
    await db.execute('UPDATE products SET status = ?, updated_at = NOW() WHERE product_id = ?', [status, id]);

    console.log(`[${formatDateTime(new Date())}] [INFO] [用户更新商品状态] 商品ID: ${id}, 新状态: ${status}, 操作人: ${userId}`);

    res.json({ success: true, message: '商品状态已更新' });
  } catch (error) {
    console.error(`[${formatDateTime(new Date())}] [ERROR] [更新商品状态失败] ${error.message}`);
    res.status(500).json({ success: false, error: '更新商品状态失败' });
  }
};

// 获取热门商品
/**
 * 获取热门商品列表（支持分页）
 * @param {Object} req - 请求对象，包含分页参数page、pageSize和可选的categoryId
 * @param {Object} res - 响应对象
 * @returns {Promise<void>} - 返回热门商品列表及分页信息
 */
exports.getHotProducts = async (req, res) => {
  try {
    const { categoryId, page = 1, pageSize = 10 } = req.query;
    const currentPage = parseInt(page, 10);
    const itemsPerPage = parseInt(pageSize, 10);
    const offset = (currentPage - 1) * itemsPerPage;

    console.log(`[${formatDateTime(new Date())}] [INFO] 获取热门商品请求: ${categoryId ? `分类ID=${categoryId}, ` : ''}页码=${currentPage}, 每页数量=${itemsPerPage}`);

    // 构建商品数据SQL查询
    let sql = `
      SELECT p.product_id, p.seller_id, p.category_id, p.title, p.description, 
             CAST(p.price AS DECIMAL(10,2)) AS price, CAST(p.original_price AS DECIMAL(10,2)) AS original_price, 
             p.status, p.view_count, p.created_at, p.updated_at, 
             (SELECT image_url FROM product_images WHERE product_id = p.product_id AND sort_order = 0 LIMIT 1) AS image_url 
      FROM products p
      WHERE p.status = 1`;

    // 构建总数量SQL查询
    let countSql = `
      SELECT COUNT(DISTINCT p.product_id) as total
      FROM products p
      WHERE p.status = 1`;

    const params = [];
    const countParams = [];

    // 添加分类筛选条件（如果提供）
    if (categoryId) {
      sql += ' AND p.category_id = ?';
      countSql += ' AND p.category_id = ?';
      params.push(categoryId);
      countParams.push(categoryId);
    }

    // 继续构建SQL
    sql += `
      GROUP BY p.product_id
      ORDER BY p.view_count DESC, p.created_at DESC
      LIMIT ? OFFSET ?
    `;
    params.push(itemsPerPage, offset);

    // 执行查询
    const [rows] = await db.query(sql, params);
    const [countResult] = await db.query(countSql, countParams);
    const totalItems = countResult[0].total;
    const totalPages = Math.ceil(totalItems / itemsPerPage);

    console.log(`[${new Date().toLocaleString()}] [INFO] 获取热门商品成功: 数量=${rows.length}, 总数量=${totalItems}, 总页数=${totalPages}`);
    res.json({
      products: rows,
      pagination: {
        currentPage,
        pageSize: itemsPerPage,
        totalItems,
        totalPages
      }
    });
  } catch (err) {
    console.error(`[${new Date().toLocaleString()}] [ERROR] 获取热门商品失败: ${err.message}`);
    res.status(500).json({ message: '获取热门商品失败', error: err.message });
  }
};
